#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mygraphicsview.h"

#include <QGraphicsRectItem>
#include <QDebug>
#include <QColorDialog>
#include <QKeyEvent>
#include <QTime>
#include <QInputDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    labViewCord = new QLabel("View坐标: ");
    labViewCord->setMinimumWidth(150);
    ui->statusbar->addWidget(labViewCord);

    labSceneCord = new QLabel("Scene坐标: ");
    labSceneCord->setMinimumWidth(150);
    ui->statusbar->addWidget(labSceneCord);

    labItemCord = new QLabel("Item坐标: ");
    labItemCord->setMinimumWidth(150);
    ui->statusbar->addWidget(labItemCord);

    ui->graphicsView->setCursor(Qt::CrossCursor);
    ui->graphicsView->setMouseTracking(true);
    ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag);

    //连接信号
    connect(ui->graphicsView, &MyGraphicsView::mouseMovePoint, this, &MainWindow::on_mouseMovePoint);
    connect(ui->graphicsView, &MyGraphicsView::mouseClicked, this, &MainWindow::on_mouseClicked);
    connect(ui->graphicsView, &MyGraphicsView::mouseDoubleClicked, this, &MainWindow::on_mouseDoubleClicked);
    connect(ui->graphicsView, &MyGraphicsView::keyPress, this, &MainWindow::on_keyPress);

    initGraphics();

    qsrand(QTime::currentTime().second());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    //
    ui->labGraphViewSize->setText(QString::asprintf("Graphics View坐标 宽:%d, 高:%d",
                                                    ui->graphicsView->width(),
                                                    ui->graphicsView->height()));
    QRectF rect = ui->graphicsView->sceneRect();
    ui->labGraphicsViewText->setText(QString::asprintf("QGraphicsView::sceneRect=(L,R,W,G)=%.0f, %.0f,%.0f,%.0f",
                                                       rect.left(),
                                                       rect.top(),
                                                       rect.width(), rect.height()));
}

void MainWindow::initGraphics()
{
    QRectF rect(-300, -100, 600, 200);

    //创建scene
    scene = new QGraphicsScene(rect);

    //view和scene绑定
    ui->graphicsView->setScene(scene);

//    QGraphicsRectItem *item = new QGraphicsRectItem(rect);
//    item->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsFocusable);

//    QPen pen;
//    pen.setWidth(2);
//    item->setPen(pen);
//    scene->addItem(item);

//    QGraphicsEllipseItem *item2 = new QGraphicsEllipseItem(-100, -50, 200, 100);
//    item2->setBrush(QBrush(Qt::blue));
////    item2->setPos(0, 0);
//    //向scene添加一个item
//    item2->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsFocusable
//                    | QGraphicsItem::ItemIsMovable);

//    scene->addItem(item2);

//    QGraphicsEllipseItem *item3 = new QGraphicsEllipseItem(-50, -50, 100, 100);
//    item3->setBrush(QBrush(Qt::red));
//    item3->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsFocusable
//                    | QGraphicsItem::ItemIsMovable);
////    item3->setPos(rect.right(), rect.bottom());
//    //向scene添加一个item
//    scene->addItem(item3);
}

void MainWindow::on_mouseMovePoint(QPoint point)
{
    labViewCord->setText(QString::asprintf("View坐标: %d,%d", point.x(), point.y()));

    QPointF pointScene = ui->graphicsView->mapToScene(point);
    labSceneCord->setText(QString::asprintf("Scene坐标: %.0f,%.0f", pointScene.x(), pointScene.y()));
}

void MainWindow::on_mouseClicked(QPoint point)
{
    QPointF pointScene = ui->graphicsView->mapToScene(point);
    QGraphicsItem *item = NULL;
    item = scene->itemAt(pointScene, ui->graphicsView->transform());
    if(item)
    {
        QPointF pointItem = item->mapFromScene(pointScene);
        labItemCord->setText(QString::asprintf("Item坐标: %.0f,%.0f", pointItem.x(), pointItem.y()));
    }
}

void MainWindow::on_mouseDoubleClicked(QPoint point)
{
    QPointF pointScene = ui->graphicsView->mapToScene(point);
    QGraphicsItem * item = NULL;
    item = scene->itemAt(pointScene, ui->graphicsView->transform());
    if(!item) return;

    switch (item->type()) {
        case QGraphicsRectItem::Type:
        case QGraphicsEllipseItem::Type:
        case QGraphicsPolygonItem::Type:
        case QGraphicsSimpleTextItem::Type:
            {
                QAbstractGraphicsShapeItem *itemRect;
                itemRect = qgraphicsitem_cast<QAbstractGraphicsShapeItem *>(item);
                QColor color = itemRect->brush().color();
                color = QColorDialog::getColor(color, NULL, "选择颜色");
                if(color.isValid()) {
                    itemRect->setBrush(QBrush(color));
                }
                break;
            }
        case QGraphicsLineItem::Type:
            {
                QGraphicsLineItem *itemRect;
                itemRect = qgraphicsitem_cast<QGraphicsLineItem *>(item);
                QColor color = itemRect->pen().color();
                color = QColorDialog::getColor(color, NULL, "选择颜色");
                if(color.isValid()) {
                    itemRect->setPen(QPen(color));
                }
                break;
            }
          default:
                break;
    }
}

void MainWindow::on_keyPress(QKeyEvent *event)
{
    int cnt = scene->selectedItems().count();
    if(!cnt) return;

    switch (event->key()) {
        case Qt::Key_Delete:
        {
            for(int i = 0; i < cnt; i++)
            {
                QGraphicsItem* item = scene->selectedItems().at(0);
                scene->removeItem(item);
            }
            break;
        }
        case Qt::Key_Left:
        {
            for(int i = 0; i < cnt; i++)
            {
                QGraphicsItem* item = scene->selectedItems().at(i);
                item->setX(item->x() - 1);
            }
            break;
        }
        case Qt::Key_Right:
        {
            for(int i = 0; i < cnt; i++)
            {
                QGraphicsItem* item = scene->selectedItems().at(i);
                item->setX(item->x() + 1);
            }
            break;
        }
        case Qt::Key_Up:
        {
            for(int i = 0; i < cnt; i++)
            {
                QGraphicsItem* item = scene->selectedItems().at(i);
                item->setY(item->y() - 1);
            }
            break;
        }
        case Qt::Key_Down:
        {
            for(int i = 0; i < cnt; i++)
            {
                QGraphicsItem* item = scene->selectedItems().at(i);
                item->setY(item->y() + 1);
            }
            break;
        }
    }
}


void MainWindow::on_actZoomIn_triggered()
{
//    int allCnt = scene->items().size();
    int cnt = scene->selectedItems().size();
    if(cnt == 0)
    {
        ui->graphicsView->scale(1.1, 1.1);
        return;
    }

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        item->setScale(0.1 + item->scale());
    }
}

void MainWindow::on_actZoomOut_triggered()
{
    int cnt = scene->selectedItems().count();
    if(cnt == 0)
    {
        ui->graphicsView->scale(0.9, 0.9);
        return;
    }

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        item->setScale(-0.1 + item->scale());
    }
}

void MainWindow::on_actRestore_triggered()
{
    int cnt = scene->selectedItems().count();
    if(cnt == 0)
    {
        ui->graphicsView->resetTransform();
        return;
    }

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        item->setScale(1);
    }
}

void MainWindow::on_actLeftRolate_triggered()
{
    int cnt = scene->selectedItems().count();
    if(cnt == 0)
    {
        ui->graphicsView->rotate(- 45);
        return;
    }

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        item->setRotation(item->rotation() - 45);
    }
}

void MainWindow::on_actRightRolate_triggered()
{
    int cnt = scene->selectedItems().count();
    if(cnt == 0)
    {
        ui->graphicsView->rotate(45);
        return;
    }

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        item->setRotation(item->rotation() + 45);
    }
}

void MainWindow::on_actEditFront_triggered()
{
    int cnt = scene->selectedItems().count();
    if(cnt == 0)
    {
        return;
    }

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        item->setZValue(item->zValue() + 1);
    }
}

void MainWindow::on_actEditBack_triggered()
{
    int cnt = scene->selectedItems().count();
    if(cnt == 0)
    {
        return;
    }

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        item->setZValue(item->zValue() - 1);
    }
}

void MainWindow::on_actGroup_triggered()
{
    int cnt = scene->selectedItems().count();
    if( !(cnt > 1))
    {
        return;
    }

    QGraphicsItemGroup *group = new QGraphicsItemGroup();
    scene->addItem(group);

    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(0);
        item->setSelected(false);
        group->addToGroup(item);
    }
    group->setFlags(QGraphicsItem::ItemIsSelectable |
                    QGraphicsItem::ItemIsMovable
                    |QGraphicsItem::ItemIsFocusable );
//    scene->clearSelection();
    group->setSelected(true);
}

void MainWindow::on_actGroupBreak_triggered()
{
    int cnt = scene->selectedItems().count();
    if( !cnt)
    {
        return;
    }

    QList<QGraphicsItemGroup *> list;
    for(int i = 0; i < cnt; i++)
    {
        QGraphicsItem* item = scene->selectedItems().at(i);
        if(item->type() == QGraphicsItemGroup::Type)
        {
            QGraphicsItemGroup* group = qgraphicsitem_cast<QGraphicsItemGroup*>(item);
            list.append(group);
        }
    }

    foreach(auto groupItem, list)
    {
        //打散group
        scene->destroyItemGroup(groupItem);
    }
}

void MainWindow::on_actRect_triggered()
{
    QGraphicsRectItem *item = new QGraphicsRectItem(-50, -30, 100, 60);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    item->setBrush(QBrush(Qt::yellow));
    item->setPos(-100 + qrand() % 200, -60 + qrand() %120);
    item->setData(ItemId, ++seqNum);
    item->setData(ItemDescription, "矩形");
    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actEllipse_triggered()
{
    auto *item = new QGraphicsEllipseItem(-50, -30, 100, 60);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    item->setBrush(QBrush(Qt::gray));
    item->setPos(-100 + qrand() % 200, -60 + qrand() %120);
    item->setData(ItemId, ++seqNum);
    item->setData(ItemDescription, "椭圆");
    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actCircle_triggered()
{
    auto *item = new QGraphicsEllipseItem(-50, -50, 100, 100);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    item->setBrush(QBrush(Qt::gray));
    item->setPos(-100 + qrand() % 200, -60 + qrand() %120);
    item->setData(ItemId, ++seqNum);
    item->setData(ItemDescription, "圆形");
    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actLine_triggered()
{
    auto *item = new QGraphicsLineItem(-100, 0, 100, 0);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    QPen pen;
    pen.setColor(Qt::black);
    pen.setWidth(3);
    item->setPen(pen);
    item->setPos(-100 + qrand() % 200, -60 + qrand() %120);
    item->setData(ItemId, ++seqNum);
    item->setData(ItemDescription, "直线");
    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actPolygon_triggered()
{
    auto *item = new QGraphicsPolygonItem;
    QPolygonF points;
    points.append(QPointF(-40, -40));
    points.append(QPointF(40, -40));
    points.append(QPointF(60, 40));
    points.append(QPointF(-60, 40));

    item->setPolygon(points);

    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    QPen pen;
    pen.setColor(Qt::black);
    pen.setWidth(3);
    item->setPen(pen);
    item->setPos(-100 + qrand() % 200, -60 + qrand() %120);
    item->setData(ItemId, ++seqNum);
    item->setData(ItemDescription, "梯形");
    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actTriangle_triggered()
{
    auto *item = new QGraphicsPolygonItem;
    QPolygonF points;
    points.append(QPointF(0, -40));
    points.append(QPointF(60, 40));
    points.append(QPointF(-60, 40));

    item->setPolygon(points);

    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    QPen pen;
    pen.setColor(Qt::red);
    pen.setWidth(3);
    item->setPen(pen);
    item->setPos(-100 + qrand() % 200, -60 + qrand() %120);
    item->setData(ItemId, ++seqNum);
    item->setData(ItemDescription, "三角形");
    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actText_triggered()
{
    QString str = QInputDialog::getText(this, "输入对话框", "请输入: ");
    auto* item = new QGraphicsSimpleTextItem(str);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    QFont font;
    font.setPointSize(20);
    item->setFont(font);
    item->setBrush(QBrush(Qt::red));
    item->setPos(-100 + qrand() % 200, -60 + qrand() %120);
    item->setData(ItemId, ++seqNum);
    item->setData(ItemDescription, "文字");
    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}
